"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : security-path-escape
Case Name   : 创建 C 类型函数时，模块路径参数是否可以通过 '../' 实现逃逸
Create At   : 2023/06/07
@zou_jialiang0501162244
Description :
    1. 创建模块路径中包含 '../' 的 C 类型函数
Expect      :
    1. 报错
History     :
"""

import os
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class PathEscape(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.cons = Constant()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.func = 'f_privilege_0036'

    def test_security(self):
        text = "-----step1:创建模块路径中包含 '../' 的 C 类型函数;expect:创建报错-----"
        self.log.info(text)
        sql = f"CREATE OR REPLACE FUNCTION {self.func}(cstring) RETURNS " \
              f"integer AS '../../../../../lib64/libc.so.6', " \
              f"'system' LANGUAGE C STRICT;"
        msg = self.pri_sh.execut_db_sql(sql)
        self.log.info(msg)
        self.assertTrue(msg.find('ERROR:') > -1, f"执行失败:{text}")

    def tearDown(self):
        text = '-----step2:清理环境 expect:成功-----'
        self.log.info(text)
        msg = self.pri_sh.execut_db_sql(
            f'DROP FUNCTION IF EXISTS {self.func};')
        self.log.info(msg)
        self.assertIn(self.cons.DROP_FUNCTION_SUCCESS_MSG, msg, f"执行失败:{text}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
